package com.example.demo.jdk.classloader;


import com.example.demo.jdk.java8.lambda.Java8Tester;

import java.io.*;

/**
 * @author WangtTao
 * @date 2020/10/29 14:38
 */
public class MyClassLoaderTest {
    static class MyClassLoader extends ClassLoader {
        private String classPath;

        public MyClassLoader(String classPath) {
            this.classPath = classPath;
        }

        public byte[] loadBytes(String name) throws IOException {
            name = name.replace(".", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                byte[] bytes = loadBytes(name);
                return defineClass(name, bytes, 0, bytes.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            throw new ClassNotFoundException();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader("F:/");
        Class<?> aClass = myClassLoader.loadClass("com.youon.ibike668.hera.item.api.model.req.CategoryReq");
        ClassLoader classLoader = aClass.getClassLoader();
        System.out.println(classLoader);

        Class<?> aClass1 = myClassLoader.loadClass("com.example.demo.jdk.java8.lambda.Java8Tester");
        ClassLoader classLoader1 = aClass1.getClassLoader();
        System.out.println(classLoader1);
    }
}
